package com.example.yilanchatserver.business.freechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.service.dto.UtopiaStreamDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.*;

@Slf4j
@Component
public class UtopiaWebClient {

    @Value("${utopia.stream}")
    private String CHAT_API;

    private WebClient webClient;




    /**
     * dev采用代理访问
     */
    @PostConstruct
    public void init() {
        initProd();
    }





    public void initProd() {
        log.info("initProd");
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .baseUrl(CHAT_API)
                .build();
    }


    public Flux<String> getChatResponse(UtopiaStreamDTO utopiaStreamDTO, String authToken) {

        Map talkerParams = JSON.parseObject(JSON.toJSONString(utopiaStreamDTO), Map.class);
        talkerParams.put("token", authToken);




        // 预先设置

//

        return webClient.get()
                .uri("/{token}?appUserId={appUserId}&roleId={roleId}&content={content}&token={token}", talkerParams)
                .retrieve()
                .bodyToFlux(String.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    HttpStatus status = ex.getStatusCode();
                    String res = ex.getResponseBodyAsString();
                    log.error("OpenAI API error: {} {}", status, res);
                    return Mono.error(new RuntimeException(res));
                });

    }

}
